package com.yaorange.springsecuirtydemo.controller;

import com.yaorange.springsecuirtydemo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/5/27
 */
@RestController
public class LoginController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @RequestMapping("/login")
    public String login(String username, String password) {
        String token = UUID.randomUUID().toString();
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        tokenService.saveToken(token, authenticate);
        return token;
    }

    /**
     * 从SecurityContextHolder获取
     * @return
     */
    @GetMapping("/getLoginUserInfo")
    public Authentication getLoginUserInfo(){
        // 从安全上下文的持有器对象中获取安全性上下文
        // 再从安全性上下文中获取当前登录用户的信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }
}
